package com.lanou.bookstore.user.dao;

import com.lanou.bookstore.user.domain.User;
import com.lanou.bookstore.utils.C3p0_utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public User findByUsername(String username) throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        String sql = "select * from tb_user where username = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, username);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            User user = new User();
            user.setUid(resultSet.getString("uid"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            user.setEmail(resultSet.getString("email"));
            user.setCode(resultSet.getString("code"));
            user.setState(resultSet.getInt("state"));
            return user;
        } else {
            return null;
        }
    }

    public User findByEmail(String email) throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        System.out.println(email);
        String sql = "select * from tb_user where email = ?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, email);
        ResultSet resultSet = ps.executeQuery();
        if (resultSet == null) {
            return null;
        }
        if (resultSet.next()) {
            User user = new User();
            user.setUid(resultSet.getString("uid"));
            user.setUsername(resultSet.getString("username"));
            user.setPassword(resultSet.getString("password"));
            user.setEmail(resultSet.getString("email"));
            user.setCode(resultSet.getString("code"));
            user.setState(resultSet.getInt("state"));
            return user;
        } else {
            return null;
        }
    }

    public void add(User form) throws SQLException {
        Connection connection = C3p0_utils.getConnection();
        String sql = "insert into tb_user values(null,?,?,?,null,null )";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, form.getUsername());
        ps.setString(2, form.getPassword());
        ps.setString(3, form.getEmail());
//        ps.setString(4, form.getCode());
//        ps.setInt(5, form.getState());
        ps.executeUpdate();
    }
}
